import { HealthData } from '../models/HealthData';
import { RiskPrediction, PredictionResult, RiskFactor } from '../models/Prediction';
import { PatientProfile } from '../models/User';
import { HealthDataService } from './HealthDataService';
import { Storage } from '@kit.StorageKit';

// 预测服务类
export class PredictionService {
  private static instance: PredictionService;
  private healthDataService: HealthDataService;
  private storageKeyPrefix = 'prediction_';

  // 单例模式
  public static getInstance(): PredictionService {
    if (!PredictionService.instance) {
      PredictionService.instance = new PredictionService();
    }
    return PredictionService.instance;
  }

  constructor() {
    this.healthDataService = HealthDataService.getInstance();
  }

  // 预测风险
  async predictRisk(patientId: string, patientProfile: PatientProfile): Promise<RiskPrediction[]> {
    try {
      const predictions: RiskPrediction[] = [];
      
      // 获取患者健康数据
      const healthData = await this.healthDataService.getAllHealthData(patientId);
      
      // 分析不同类型的健康数据，生成预测
      predictions.push(...await this.analyzeBloodSugarRisk(patientId, healthData, patientProfile));
      predictions.push(...await this.analyzeBloodPressureRisk(patientId, healthData, patientProfile));
      predictions.push(...await this.analyzeHeartRateRisk(patientId, healthData, patientProfile));
      
      // 保存预测结果
      await this.savePredictions(predictions);
      
      // 返回高风险和关键风险的预测
      return predictions.filter(pred => pred.riskLevel === 'high' || pred.riskLevel === 'critical');
    } catch (error) {
      console.error('预测风险失败:', error);
      return [];
    }
  }

  // 分析血糖风险
  private async analyzeBloodSugarRisk(patientId: string, healthData: HealthData[], patientProfile: PatientProfile): Promise<RiskPrediction[]> {
    const predictions: RiskPrediction[] = [];
    const bloodSugarData = healthData.filter(d => d.type === 'bloodSugar' && typeof d.value === 'number');
    
    // 检查是否有糖尿病
    const hasDiabetes = patientProfile.diseases.some(d => 
      d.name.toLowerCase().includes('糖尿病') || d.name.toLowerCase().includes('diabetes')
    );
    
    if (bloodSugarData.length > 0) {
      const latestReading = bloodSugarData[0];
      const latestValue = latestReading.value as number;
      
      // 糖尿病患者的风险判断
      if (hasDiabetes) {
        if (latestValue > 11.1) { // 高血糖
          predictions.push({
            id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
            patientId,
            type: 'bloodSugar',
            riskLevel: 'high',
            predictedTime: new Date(Date.now() + 2 * 60 * 60 * 1000), // 2小时后
            confidence: 0.85,
            factors: [
              { name: '血糖值', value: latestValue, impact: 0.7 },
              { name: '糖尿病史', value: '有', impact: 0.3 }
            ],
            recommendations: ['立即测量血糖', '联系医生', '避免高糖食物'],
            isHandled: false
          });
        } else if (latestValue < 3.9) { // 低血糖
          predictions.push({
            id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
            patientId,
            type: 'bloodSugar',
            riskLevel: 'critical',
            predictedTime: new Date(Date.now() + 30 * 60 * 1000), // 30分钟后
            confidence: 0.9,
            factors: [
              { name: '血糖值', value: latestValue, impact: 0.8 },
              { name: '糖尿病史', value: '有', impact: 0.2 }
            ],
            recommendations: ['立即补充糖分', '休息', '如不适加重请就医'],
            isHandled: false
          });
        }
      }
    }
    
    return predictions;
  }

  // 分析血压风险
  private async analyzeBloodPressureRisk(patientId: string, healthData: HealthData[], patientProfile: PatientProfile): Promise<RiskPrediction[]> {
    const predictions: RiskPrediction[] = [];
    const bloodPressureData = healthData.filter(d => d.type === 'bloodPressure');
    
    if (bloodPressureData.length > 0) {
      const latestReading = bloodPressureData[0];
      const bp = latestReading.value as { systolic: number; diastolic: number };
      
      // 高血压风险判断
      if (bp.systolic > 180 || bp.diastolic > 120) { // 高血压危象
        predictions.push({
          id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
          patientId,
          type: 'bloodPressure',
          riskLevel: 'critical',
          predictedTime: new Date(Date.now() + 60 * 60 * 1000), // 1小时后
          confidence: 0.95,
          factors: [
            { name: '收缩压', value: bp.systolic, impact: 0.6 },
            { name: '舒张压', value: bp.diastolic, impact: 0.4 }
          ],
          recommendations: ['立即就医', '保持冷静', '避免剧烈活动'],
          isHandled: false
        });
      } else if (bp.systolic > 140 || bp.diastolic > 90) { // 高血压
        predictions.push({
          id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
          patientId,
          type: 'bloodPressure',
          riskLevel: 'high',
          predictedTime: new Date(Date.now() + 4 * 60 * 60 * 1000), // 4小时后
          confidence: 0.8,
          factors: [
            { name: '收缩压', value: bp.systolic, impact: 0.6 },
            { name: '舒张压', value: bp.diastolic, impact: 0.4 }
          ],
          recommendations: ['遵医嘱服药', '减少盐分摄入', '监控血压'],
          isHandled: false
        });
      }
    }
    
    return predictions;
  }

  // 分析心率风险
  private async analyzeHeartRateRisk(patientId: string, healthData: HealthData[], patientProfile: PatientProfile): Promise<RiskPrediction[]> {
    const predictions: RiskPrediction[] = [];
    const heartRateData = healthData.filter(d => d.type === 'heartRate' && typeof d.value === 'number');
    
    if (heartRateData.length > 0) {
      const latestReading = heartRateData[0];
      const heartRate = latestReading.value as number;
      
      // 心率异常风险判断
      if (heartRate > 100) { // 心动过速
        predictions.push({
          id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
          patientId,
          type: 'heartRate',
          riskLevel: 'moderate',
          predictedTime: new Date(Date.now() + 3 * 60 * 60 * 1000), // 3小时后
          confidence: 0.75,
          factors: [
            { name: '心率', value: heartRate, impact: 1.0 }
          ],
          recommendations: ['休息', '避免咖啡因', '如持续异常请就医'],
          isHandled: false
        });
      } else if (heartRate < 60) { // 心动过缓
        predictions.push({
          id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
          patientId,
          type: 'heartRate',
          riskLevel: 'moderate',
          predictedTime: new Date(Date.now() + 3 * 60 * 60 * 1000), // 3小时后
          confidence: 0.7,
          factors: [
            { name: '心率', value: heartRate, impact: 1.0 }
          ],
          recommendations: ['注意观察', '避免突然站立', '如出现头晕请就医'],
          isHandled: false
        });
      }
    }
    
    return predictions;
  }

  // 获取预测结果
  async getPredictionResult(patientId: string, dataType: string): Promise<PredictionResult> {
    try {
      // 获取历史数据
      const healthData = await this.healthDataService.getHealthDataByType(patientId, dataType);
      
      // 生成预测（简化版本，实际应用中应使用复杂的机器学习算法）
      const next24h = this.generateMockPrediction(healthData, 24);
      const next7d = this.generateMockPrediction(healthData, 7);
      const trend = this.analyzeTrend(healthData);
      
      return {
        type: dataType as any,
        next24h,
        next7d,
        trend,
        riskAssessment: this.generateRiskAssessment(trend, healthData)
      };
    } catch (error) {
      console.error('获取预测结果失败:', error);
      return {
        type: dataType as any,
        next24h: [],
        next7d: [],
        trend: 'stable',
        riskAssessment: '无法评估风险'
      };
    }
  }

  // 生成模拟预测数据
  private generateMockPrediction(healthData: HealthData[], points: number): number[] {
    const predictions: number[] = [];
    
    if (healthData.length === 0) {
      return predictions;
    }
    
    // 获取最新值作为基准
    const latestValue = typeof healthData[0].value === 'number' 
      ? healthData[0].value 
      : (healthData[0].value as any).systolic || 0;
    
    // 生成波动的预测值
    for (let i = 0; i < points; i++) {
      // 添加一些随机波动
      const variation = (Math.random() - 0.5) * 0.1 * latestValue;
      predictions.push(latestValue + variation);
    }
    
    return predictions;
  }

  // 分析趋势
  private analyzeTrend(healthData: HealthData[]): 'stable' | 'increasing' | 'decreasing' | 'fluctuating' {
    if (healthData.length < 3) {
      return 'stable';
    }
    
    // 简化的趋势分析
    const values: number[] = healthData.slice(0, 10).map(d => 
      typeof d.value === 'number' ? d.value : (d.value as any).systolic || 0
    );
    
    // 计算斜率
    const firstValue = values[values.length - 1];
    const lastValue = values[0];
    const change = lastValue - firstValue;
    const percentChange = Math.abs(change / firstValue) * 100;
    
    if (percentChange < 5) {
      return 'stable';
    } else if (change > 0) {
      return 'increasing';
    } else {
      return 'decreasing';
    }
  }

  // 生成风险评估
  private generateRiskAssessment(trend: string, healthData: HealthData[]): string {
    if (healthData.length === 0) {
      return '数据不足，无法评估风险';
    }
    
    switch (trend) {
      case 'increasing':
        return '数据呈上升趋势，需要密切关注并采取相应措施';
      case 'decreasing':
        return '数据呈下降趋势，如为异常下降需及时就医';
      case 'fluctuating':
        return '数据波动较大，建议保持规律监测';
      default:
        return '数据相对稳定，继续保持良好习惯';
    }
  }

  // 保存预测结果
  private async savePredictions(predictions: RiskPrediction[]): Promise<void> {
    try {
      for (const prediction of predictions) {
        await Storage.setOrCreate(
          this.storageKeyPrefix + prediction.id,
          JSON.stringify(prediction)
        );
      }
    } catch (error) {
      console.error('保存预测结果失败:', error);
    }
  }

  // 标记预测为已处理
  async markPredictionAsHandled(predictionId: string): Promise<boolean> {
    try {
      const predictionData = await Storage.get(this.storageKeyPrefix + predictionId);
      if (predictionData) {
        const prediction = JSON.parse(predictionData) as RiskPrediction;
        prediction.isHandled = true;
        await Storage.setOrCreate(this.storageKeyPrefix + predictionId, JSON.stringify(prediction));
        return true;
      }
      return false;
    } catch (error) {
      console.error('标记预测为已处理失败:', error);
      return false;
    }
  }
}